<?php

/**
 * Container class, item container data and retrieve db info.
 * @package item
 * @author alcaitiff
 */

class Container extends ExportableObject
{
	
	private 
            /**
             * @var Item
             */
            $item,
            $itemsNames;
	protected 
            /**
             * @var Item[]
             */
            $items=array(),
            $loaded=0;

	/**
     *
     * @param Item $item
     * @param int $capacity
     */
	function __construct ($item){
		$this->item=$item;
		$this->retrieveItems();
	}
	/**
     *
     * @param string $itemName
     * @param int $itemIndex
     * @return Item
     */
	public function getItemByName($itemName,$itemIndex){
		$items=Utils::arraySearch($this->itemsNames,$itemName,$itemIndex+1);
		
		if(count($items)>=$itemIndex){
			//found!
			$item=$this->items[key(array_slice($items,$itemIndex-1,1,TRUE))];
			return $item;
		}else{
            if($itemIndex>1){
                $itemStr=$itemName.'['.$itemIndex.']';
            }else{
                $itemStr=$itemName;
            }
		    MessageSystem::addErrorMessage($itemStr.' not found in '.  $this->item->type);
			return null;
		}
		
	}
    /**
     * Try to put a new item inside
     * @param Item $item
     */
    public function addItem($item){
        if($this->item->capacity<$this->loaded+$item->volume){
            MessageSystem::addErrorMessage('This container have '.($this->item->capacity-$this->loaded).' free space units and this item have '.$item->volume.' space units');
            return false;
        }else{
            if($item->isStackable()){
                foreach($this->items as $old){
                    if($old->getType()==$item->getType()){
                        if($old->merge($item)){
                            return true;
                            break;
                        }
                    }
                }
            }
            return $this->insertItem($item->getId());
        }
    }
    /**
     * Remove an item from container
     * @param Item $item
     * @return bool
     */
    public function removeItem($item){
        return $this->deleteItem($item->getId());
    }
    //***********************************************************************************************************
    //					DATABASE METHODS
    //***********************************************************************************************************
	/**
     * Retrieve the items from DB
     * @return void
     */
    private function retrieveItems(){

		$this->itemsNames=array();
		
		$dbo=new DB();
		$db=$dbo->db;
		$stmt = $db->prepare(	'SELECT `item` '.
								' FROM `container` '.
								'WHERE `container_item` = ? '
								);
		$id=$this->item->id;
	    $stmt->bind_param("i", $id);
	    $stmt->bind_result($itemId);
	    $stmt->execute();
		while($stmt->fetch()){
			$item=new Item($itemId);
	    	$this->items[$itemId]=$item;
	    	$this->loaded+=$item->volume;
	    	$this->item->addVolumeAndWeight($item->volume,$item->weight);
   			$this->itemsNames[$itemId]=$item->type;
  		}
  		$stmt->close(); 
	}
    /**
     * Delete an item from DB
     * @param int $id
     */
    private function deleteItem($id){
        $containerId=$this->item->getId();
        $dbo=new DB();
		$db=$dbo->db;
        $stmt = $db->prepare('DELETE FROM `container` WHERE `item`=? and `container_item`=?');
	    $stmt->bind_param("ii", $id,  $containerId);
	    $stmt->execute();
        $ret = $stmt->affected_rows;
        $stmt->close();
        return $ret;
    }
    /**
     * Insert an item in DB
     * @param int $id
     */
    private function insertItem($id){
        $containerId=$this->item->getId();
        $dbo=new DB();
		$db=$dbo->db;
        $stmt = $db->prepare('INSERT INTO `container` (`item`,`container_item`) VALUES (?,?)');
	    $stmt->bind_param("ii", $id,  $containerId);
	    $stmt->execute();
        $ret = $stmt->affected_rows;
        $stmt->close();
        return $ret;
    }
}